import 'package:flutter/material.dart';
import 'package:flutter_menu/biz/order/detail/option/options_controller.dart';
import 'package:flutter_menu/data/provider/product_provider.dart';
import 'package:flutter_menu/model/product_model.dart';
import 'package:get/get.dart';

class PackageController extends GetxController {
  PackageController({this.options = const []});

  final List<Food> options;

  OptionsController optionController = OptionsController.to;
  ProductProvider productProvider = Get.find<ProductProvider>();

  RxList<CombineFoodWithSpec> combineList = <CombineFoodWithSpec>[].obs;

  @override
  void onInit() {
    super.onInit();

    getSpecList();
  }

  Future<void> getSpecList() async {
    for (var food in options) {
      var productId = food.productId;
      var specsId = food.specsId;

      if (productId != null) {
        var productModel = await productProvider.getProductByIdAsync(productId);

        if (productModel != null) {
          var name = productModel.name;
          // 在产品的规格中查找对应的 specId
          final spec =
              productModel.specs.firstWhereOrNull((spec) => spec.id == specsId);

          if (spec != null && !spec.isStopSpec()) {
            combineList
                .add(CombineFoodWithSpec(name: name, food: food, spec: spec));
          }
        }
      }
    }
  }

  List<SelectedProduct> getSelectedProductByGroupId(String groupId) {
    return optionController.getSelectedProductByGroupId(groupId);
  }

  void removeProductInGroup(String? groupId, String? productId) {
    return optionController.removeProductInGroup(groupId, productId);
  }

  bool isProductExceedLimit(String? groupId, String? productId, int max) {
    return optionController.isProductExceedLimit(groupId, productId, max);
  }
}

class CombineFoodWithSpec {
  final String? name;
  final Food food;
  final Spec spec;

  CombineFoodWithSpec({this.name, required this.food, required this.spec});

  @override
  String toString() {
    return 'CombineFoodWithSpec{name: $name, food: $food, spec: $spec}';
  }
}
